package com.sso.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: TongRui乀
 * @Date: 2020-03-23 14:47
 * @description：
 */
@RestController
public class SecurityController {

    /**
     *  session 中缓存的请求信息
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     *  处理重定向
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     *  拦截到未登录 响应信息
     * @param request
     * @param response
     */
    @GetMapping("preLoginHandler")
    private Map<String, String> preLoginHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //判断重定向前的url是访问的页面还是rest接口
        /*SavedRequest savedRequest = requestCache.getRequest(request, response);

        String redirectUrl = savedRequest.getRedirectUrl();

        if(StringUtils.isNotBlank(redirectUrl) && redirectUrl.endsWith(".html")){
            redirectStrategy.sendRedirect(request,response, "/login.html");
        }

        HashMap<String, String> map = new HashMap<>();

        map.put("code", "1000");
        map.put("message", "检测到为登录，请先登录！");

        return map;*/
        redirectStrategy.sendRedirect(request,response, "/login.html");
        return null;
    }

}
